<?php

/*
 * 为商城首页控制器
 * @author <!--blakefan 1621743934@qq.com -->
 */
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller 
{
 	   public function index()
 	   {    
 	   	    //获取分享者uid 
 	   	    if(empty($_SESSION['pid'])){
 	   	    	$pid=I('get.uid',0,'strip_tags');
				$_SESSION['pid']=$pid;
 	   	    }
 	   		
			if(empty($_SESSION['uid']))
			{
				$this->getUser();
			}

 	   		$Index=D('index');
 	   		$result=$Index->index();
 	   		$this->assign('typetree',$result['typetree']);
 	   		$this->assign('hotitem',$result['hotitem']);
 	   		$this->assign('banner',$result['banner']);
 	   		$this->display('index');
 	   }
 	   protected function getUser(){
 	   		
 	   		$wechat=new \Org\Util\Chat();
 	   		
			if(empty($_GET['code']))
			{ 
              $re=$wechat->chat();
    		}else
    		{
    			$chat=$wechat->getuserinfo($_GET['code']);
    			
	    		//检测此微信号是否注册过
	    		$where['openid']=$chat['openid'];
	    		
	    		$users=M('user')->where($where)->find();
	    		
	    		if(!empty($users))
	    		{
	    			//此微信号已注册过，将会员信息保存到session 中
	    			$_SESSION['uid']=$users['uid'];

	    			$_SESSION['openid']=$chat['openid'];	
	    		}else{
	    			//如果此微信号没有注册过,将此微信号加入数据库中
		    		$weuser=M('user');
		    		$weuser->addtime=time();
		    		$weuser->pid=!empty($_SESSION['pid'])?$_SESSION['pid']:0;
		    		$weuser->openid=$chat['openid'];
		    		$weuser->nickname=$chat['nickname'];
		    		$weuser->headimgurl=$chat['headimgurl'];
		    		$result=$weuser->add();
		    		//将uid保存到session 
		    		$_SESSION['uid']=$result;
	    		}
    		}
 	   }
}